package org.apache.derby.iapi.services.property;

import com.czy.model.OP;
import com.czy.util.StringUtil;
import org.apache.derby.iapi.services.monitor.ModuleFactory;
import org.apache.derby.iapi.services.monitor.Monitor;

import java.util.Properties;

/**
 * @author ex_chenzy59
 * @since 2025/3/6
 *
 */
public class PropertyUtil {
    public static String getSystemProperty(String key) {
        return getSystemProperty(key, null);
    }
    public static String getSystemProperty(String key, String defaultValue) {
        var monitor = getMonitorLite();
        return OP.ofNullable(monitor.getJVMProperty(key))
                .or(()->{
                    var properties=monitor.getApplicationProperties();
                    if (properties==null){
                        return null;
                    }
                    return properties.getProperty(key);
                }).orElse(defaultValue);
    }
    private  static  ModuleFactory  getMonitorLite(){
        return Monitor.getMonitorLite();
    }
    public static int getSystemInt(String key, int defaultValue) {
        return getSystemInt(key, 0, Integer.MAX_VALUE, defaultValue);
    }
    public static int getSystemInt(String key, int min, int max, int defaultValue) {
        return handleInt(getSystemProperty(key), min, max, defaultValue);
    }
    public static int handleInt(String value, int min, int max, int defaultValue) {
        var intValue=StringUtil.getInt(value,defaultValue);
        return (intValue >= min) && (intValue <= max) ? intValue : defaultValue;
    }
    public static boolean getSystemBoolean(String key) {
        return getSystemBoolean(key, false);
    }
    public static boolean getSystemBoolean(String key, boolean defaultValue) {
        String value = PropertyUtil.getSystemProperty(key);
        return value == null ? defaultValue : (Boolean.parseBoolean(value.trim()));
    }

}
